<?php
/**
 * User: wanghousheng
 * Date: 2017/8/23
 * Time: 09:57
 */

namespace Xiaoc\Api;

use PhalApi\Exception\BadRequestException;
use PhalApi\Api;

class Common extends Api
{
    protected $di;
    protected $medoo;
    protected $notorm;
    protected $nowPage;//当前页数
    protected $limitStart;//分页查询limit初始值
    protected $limitEnd = 20;//每页显示多少条记录

    public function __construct()
    {
        $this->di = \PhalApi\DI();
        $this->medoo = $this->di->medoo;
        $this->notorm = $this->di->notorm;
        $this->nowPage = intval(ApiGet('page')) ? intval(ApiGet('page')) : 1;
        $this->limitStart = $this->limitEnd * ($this->nowPage - 1);
    }

    /**
     * 获取系统配置参数值
     * @param $code shop_config/code字段
     * @return string
     */
    protected function getConfig($code)
    {
        if ($code) {
            $config = \PhalApi\DI()
                ->notorm
                ->shop_config
                ->select('value')
                ->where('code', $code)
                ->fetchOne();
            return isset($config['value']) ? $config['value'] : '';
        }
    }

    /**
     * Name: 判断是不是有下一页
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $count
     * @return bool
     */
    protected function HasMore($count)
    {
        $hasmore = false;
        if (intval($count) > 0) {
            $totalPages = ceil($count / $this->limitEnd);
            if ($this->nowPage < $totalPages) {
                $hasmore = true;
            }
        }
        return $hasmore;
    }

    /**
     * Name: 获取用户密码
     * User: wanghousheng
     * Date: 2016/12/27
     * @return array
     */
    protected function user_password($cfg)
    {
        if (isset($cfg['password'])) {
            $cfg['md5password'] = md5($cfg['password']);
        }

        if (empty($cfg['type'])) {
            $cfg['type'] = PWD_MD5;
        }

        switch ($cfg['type']) {
            case PWD_MD5:
                if (!empty($cfg['ec_salt'])) {
                    return md5($cfg['md5password'] . $cfg['ec_salt']);
                } else {
                    return $cfg['md5password'];
                }
            case PWD_PRE_SALT:
                if (empty($cfg['salt'])) {
                    $cfg['salt'] = '';
                }

                return md5($cfg['salt'] . $cfg['md5password']);
            case PWD_SUF_SALT:
                if (empty($cfg['salt'])) {
                    $cfg['salt'] = '';
                }

                return md5($cfg['md5password'] . $cfg['salt']);
            default:
                return '';
        }
    }

    /**
     * Name: 生成用户token
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $user_info
     */
    protected function SetToken($user_id)
    {
        if ($user_id) {
            return md5($user_id . strval(time()));
        }
    }

    /**
     * Name: 登录成功之后修改用户信息
     * User: wanghousheng
     * Date: 2016/12/27
     */
    protected function update_login($users)
    {
        if ($users) {
            $where['user_id'] = $users['user_id'];
            $updata['visit_count'] = $users['visit_count'] + 1;
            $updata['last_ip'] = getIp();
            $updata['last_login'] = time();
            $this->medoo->update('users', $updata, $where);
            $token = $this->SetToken($users['user_id']);
            $tokens = $this->di->cache->get($users['user_id']);
            if ($tokens) {
                $tokens[] = $token;
            } else {
                $tokens = array($token);
            }
            $this->di->cache->set($users['user_id'], $tokens, 3600 * 24 * 365);
            //保存缓存中
            $this->di->cache->set($token, $users, 3600 * 24 * 365);
            return $token;
        }
    }

    /**
     * Name: 接口返回错误信息
     * User: wanghousheng
     * Date: 2016/12/27
     * @param string $msg
     */
    protected function api_error_msg($msg = '未知错误', $code = 400)
    {
        throw new BadRequestException($msg, $code);
    }

    /**
     * Name: 接口返回正确信息
     * User: wanghousheng
     * Date: 2016/12/27
     * @param string $msg
     */
    protected function api_success_msg($msg = '操作成功')
    {
        throw new SuccessRequestException($msg, 200);
    }

    /**
     * Name: 检查登录
     * User: wanghousheng
     * Date: 2016/12/27
     * @return mixed
     */
    protected function check_login($token = '')
    {
        if (empty($token)) $token = ApiGet('user_token');
        if ($token) {
            $user_info = $this->di->cache->get($token);
            if ($user_info['user_id']) {
                $tokens = $this->di->cache->get($user_info['user_id']);
                if (!$tokens || count($tokens) > 3) {
                    $this->api_error_msg('你的账号已在多个设备登录', 1);
                }
                return $user_info;
            }
        }
        $this->api_error_msg('请登录', 1);
    }

    /**
     * Name: 获取用户信息
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $token
     * @return array|mixed
     */
    protected function get_users_info($token)
    {
        $user_info = $this->di->cache->get($token);
        if ($user_info['user_id']) {
            $where['user_id'] = $user_info['user_id'];
            $visit_count = $this->medoo->get('users', 'visit_count', $where);
            if ($visit_count != $user_info['visit_count']) {
                $this->di->cache->delete($token);
                return array();
            } else {
                return $user_info;
            }
        }
    }

    /**
     * Name: 检查用户手机号是不是存在
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $mobile
     * @return bool
     */
    protected function check_user_mobile($mobile)
    {
        if ($mobile) {
            $where['mobile_phone'] = trim($mobile);
            $res = $this->di->medoo->get('users', 'mobile_phone', $where);
            if ($res) return true;
        }
        return false;
    }

    /**
     * Name: 获取QQ配置信息
     * User: wanghousheng
     * Date: 2016/12/27
     * @return array
     */
    protected function get_oauth_qq()
    {
        $where['type'] = 'qq';
        $where['status'] = 1;
        $config = array();
        $oauth = $this->medoo->get('touch_auth', 'auth_config', $where);
        if ($oauth) {
            $oauth_config = unserialize($oauth);
            if ($oauth_config) {
                foreach ($oauth_config as $value) {
                    if ($value['name'] == 'app_id') {
                        $config['APIId'] = $value['value'];
                    } elseif ($value['name'] == 'app_key') {
                        $config['APIKEY'] = $value['value'];
                    } else {
                        continue;
                    }
                }
            }
            if (empty($config['APIId']) || empty($config['APIKEY'])) $config = array();
        }
        return $config;
    }

    /**
     * Name: 统计订单
     * User: wanghousheng
     * Date: 2016/12/27
     * @param int $user_id
     * @param int $show_type
     * @param string $where
     */
    protected function get_order_where_count($user_id = 0, $show_type = 0, $where = '')
    {
        $pre = get_table_prefix();
        $sql = 'SELECT COUNT(*)  FROM ' . $pre . 'order_info as oi' . ' WHERE oi.user_id = \'' . $user_id . '\' and oi.is_delete = \'' . $show_type . '\'' . ' and (select count(*) from ' . $pre . 'order_info' . ' as oi_2 where oi_2.main_order_id = oi.order_id) = 0 ' . ' AND oi.is_zc_order = 0 ' . $where;
        $conut = $this->notorm->order_info->queryAll($sql);
        return $conut[0]['COUNT(*)'];

    }

    /**
     * Name:获取用户手机号
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $user_id
     * @return string
     */
    protected function get_user_mobile($user_id)
    {
        if ($user_id) {
            $where['user_id'] = $user_id;
            $res = $this->di->medoo->get('users', 'mobile_phone', $where);
            if ($res) {
                return $res;
            }
        }
        return '';
    }

    /**
     * 递归
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $cate
     * @param string $name
     * @param int $pid
     * @return array
     */
    protected function AreaLayer($cate, $name = 'child', $pid = 1)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v[$name] = $this->areaLayer($cate, $name, $v['id']);
                unset($v['pid']);
                $arr[] = $v;
            }
        }
        return $arr;
    }

    /**
     * Name: 获取地区名称
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $province
     * @param $city
     * @param $district
     * @return string
     */
    protected function get_address($province, $city, $district)
    {
        $address = '';
        $province = intval($province);
        $city = intval($city);
        $district = intval($district);
        if ($province && $city && $district) {
            $where['region_id'] = array($province, $city, $district);
            $list = $this->medoo->select('region', array('region_name'), $where);
            foreach ($list as $value) {
                $address .= $value['region_name'];
            }
        }
        return $address;
    }

    /**
     * Name: 获取店铺名称头像
     * User: wanghousheng
     * Date: 2016/12/27
     * @param int $ru_id
     * @return mixed
     */
    protected function get_shop_name($ru_id = 0)
    {
        $shop_where['ru_id'] = intval($ru_id);
        $shop_info = $this->medoo->get('seller_shopinfo', array('check_sellername', 'shop_name', 'shopname_audit', 'brand_thumb'), $shop_where);
        $shop_informatio = $this->medoo->get('merchants_shop_information', array('#CONCAT(shoprz_brandName,shopNameSuffix)(shop_name)', 'rz_shopName'), array('user_id' => $ru_id));
        if ($shop_info['shopname_audit'] == 1) {
            if ($shop_info['check_sellername'] == 1) {
                $shop_name = $shop_informatio['rz_shopname'];
            } else if ($shop_info['check_sellername'] == 2) {
                $shop_name = $shop_info['shop_name'];
            } else if (0 < $ru_id) {
                $shop_name = $shop_informatio['shop_name'];
            } else {
                $shop_name = $shop_info['shop_name'];
            }
        } else {
            $shop_name = $shop_informatio['rz_shopname'];
        }
        $info['collect_number'] = $this->medoo->count('collect_store', 'ru_id', array('ru_id' => $ru_id));
        $info['shop_name'] = $shop_name;
        $info['brand_thumb'] = $shop_info['brand_thumb'];
        return $info;
    }

    /**
     * Name: 获取订单下商品
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $order_id
     * @return array
     */
    protected function get_order_goods($order_id)
    {
        $order_id = intval($order_id);
        if ($order_id) {
            $join['[>]goods'] = array('goods_id');
            $where['order_goods.order_id'] = $order_id;
            $field = array('goods.goods_thumb', 'order_goods.goods_name', 'order_goods.goods_number', 'order_goods.goods_price', 'order_goods.goods_id', 'order_goods.rec_id', 'order_goods.goods_attr');
            $where['ORDER'] = array('order_goods.rec_id' => 'DESC');
            $list = $this->medoo->select('order_goods', $join, $field, $where);
            if ($list) {
                return $list;
            }
        }
        return array();
    }

    /**
     * Name: 获取订单状态
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $order
     */
    protected function get_order_status($order, $sign = 0)
    {
        $return = 0;
        $is_del = 0;
        $status = 0;
        $is_pay = 0;
        $lang = $this->order_lang();
        if ($order['order_status'] == 0) {
            $status = 1;//取消
        } elseif ($order['order_status'] == 5) {
            if ($order['shipping_status'] == 1) {
                $status = 2;//确认收货
            } elseif ($order['shipping_status'] == 2 && $order['sign1'] == 0) {
                $status = 3;//评论
            } elseif ($order['pay_status'] == 0 || $order['pay_status'] == 3 && $order['order_amount'] > 0) {
                $is_pay = 1;//立即付款
            }
        } else {
            if ($order['pay_status'] == 0 && $order['shipping_status'] == 0) {
                $status = 1;//取消
            }
        }
        if ($order['order_status'] == 1 && $order['order_amount'] > 0 && $order['pay_status'] == 0 || $order['pay_status'] == 3) {
            $is_pay = 1;//立即付款
        }
        if ($order['order_status'] == 0 && $order['order_amount'] > 0 && $order['pay_status'] == 0 || $order['pay_status'] == 3) {
            $is_pay = 1;//立即付款
        }
        if ($order['order_status'] == 5 && $order['shipping_status'] == 2 && $order['pay_status'] == 2 && $order['sign1'] == 0) {
            $status = 3;//评论
            $return = 1;//申请售后
        } else {
            if ($order['order_status'] == 2 && $order['shipping_status'] == 0 && $order['pay_status'] == 0) {
                $status = 0;
            } else {
                if ($order['order_status'] == 1 && $order['shipping_status'] == 2 && $order['shipping_status'] == 2 && $order['sign1'] == 0) {
                    $status = 3;//评论
                    $return = 1;//申请售后
                }
            }
        }
        if (($order['order_status'] == 2) || (($order['order_status'] == 5) && ($order['shipping_status'] == 2) && ($order['pay_status'] == 2))) {
            $is_del = 1;
        }
        if (0 < $sign) {
            $time = gmtime();
            $day = ($time - $order['pay_time']) / 3600 / 24;
            if (($order['order_status'] != OS_CANCELED) && ($order['pay_status'] == PS_PAYED)) {
                if ($day < $sign) {
                    $return = 1;//申请售后
                }
            }
        }
        $order_text = $lang['os'][$order['order_status']] . ' ' . $lang['ps'][$order['pay_status']] . ' ' . $lang['ss'][$order['shipping_status']];
        if (($order['order_status'] == OS_SPLITED) && ($order['shipping_status'] == SS_RECEIVED) && ($order['pay_status'] == PS_PAYED)) {
            $order_text = '已完成';
        } else {
            if (($order['order_status'] == OS_CANCELED) && ($order['shipping_status'] == SS_UNSHIPPED) && ($order['pay_status'] == PS_UNPAYED)) {
                $order_text = $lang['os'][OS_CANCELED];
            } else {
                if (($order['order_status'] == OS_SPLITED) && ($order['shipping_status'] == SS_SHIPPED) && ($order['pay_status'] == PS_PAYED)) {

                } else {
                    if (($order['order_status'] == OS_CONFIRMED) && ($order['shipping_status'] == SS_RECEIVED) && ($order['pay_status'] == PS_PAYED)) {
                        $order_text = '已完成';
                    }
                }
            }
        }
        $data['is_pay'] = $is_pay;
        $data['status'] = $status;
        $data['is_del'] = $is_del;
        $data['return'] = $return;
        $data['order_text'] = $order_text;
        return $data;
    }

    /**
     * Name: 修改商品库存
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $order_id
     */
    protected function change_order_goods_storage($order_id, $is_dec = false)
    {
        if ($order_id > 0) {
            $order_goods_where['order_id'] = $order_id;
            $order_goods_where['GROUP'] = array('goods_id', 'product_id');
            $order_goods_where['is_real'] = 1;
            $order_goods_field = array('goods_id', '#SUM(goods_number)(num)', 'product_id', 'warehouse_id', 'area_id', 'ru_id');
            $order_goods = $this->medoo->select('order_goods', $order_goods_field, $order_goods_where);
            if ($order_goods) {
                foreach ($order_goods as $key => $value) {
                    $is_real = $this->medoo->get('goods', 'is_real', array('goods_id' => $value['goods_id']));
                    if ($is_dec) {
                        return $this->change_goods_storage($value['goods_id'], $value['product_id'], 0 - ($value['num']), $value['warehouse_id'], $value['area_id'], $order_id, $value['ru_id']);
                    } elseif ($is_real) {
                        return $this->change_goods_storage($value['goods_id'], $value['product_id'], $value['num'], $value['warehouse_id'], $value['area_id'], $order_id, $value['ru_id']);
                    }
                }
            }
        }
    }

    //修改库存
    private function change_goods_storage($goods_id = 0, $product_id = 0, $number = 0, $warehouse_id = 0, $area_id = 0, $order_id = 0, $store_id = 0)
    {
        if ($number == 0) {
            return true;
        }
        if (empty($goods_id) || empty($number)) {
            return false;
        }
        $prefix = get_table_prefix();
        $number = (0 < $number ? '+ ' . $number : $number);
        $goods = $this->medoo->get('goods', array('model_inventory', 'model_attr'), array('goods_id' => $goods_id));
        $abs_number = abs($number);
        if ($product_id) {
            $where = '';
            if (isset($store_id) && (0 < $store_id)) {
                $table_products = 'store_products';
                $where = ' AND store_id = \'' . $store_id . '\'';
            } else if ($goods['model_attr'] == 1) {
                $table_products = 'products_warehouse';
                $table = $this->notorm->products_warehouse;
            } else if ($goods['model_attr'] == 2) {
                $table_products = 'products_area';
                $table = $this->notorm->products_area;
            } else {
                $table_products = 'products';
                $table = $this->notorm->products;
            }
            if ($number < 0) {
                $set_update = 'IF(product_number >= ' . $abs_number . ', product_number ' . $number . ', 0)';
            } else {
                $set_update = 'product_number ' . $number;
            }
            $sql = 'UPDATE ' . $prefix . $table_products . "\r\n                SET product_number = " . $set_update . "\r\n                WHERE goods_id = '" . $goods_id . "'\r\n                AND product_id = '" . $product_id . "'\r\n   '" . $where . "'     LIMIT 1";
            $table->queryAll($sql);
        } else {
            if ($number < 0) {
                if (0 < $store_id) {
                    $set_update = 'IF(goods_number >= ' . $abs_number . ', goods_number ' . $number . ', 0)';
                } else {
                    if ($goods['model_inventory'] == 1 || $goods['model_inventory'] == 2) {
                        $set_update = 'IF(region_number >= ' . $abs_number . ', region_number ' . $number . ', 0)';
                    } else {
                        $set_update = 'IF(goods_number >= ' . $abs_number . ', goods_number ' . $number . ', 0)';
                    }
                }
            } elseif (0 < $store_id) {
                $set_update = 'goods_number ' . $number;
            } else {
                if (($goods['model_inventory'] == 1) || ($goods['model_inventory'] == 2)) {
                    $set_update = 'region_number ' . $number;
                } else {
                    $set_update = 'goods_number ' . $number;
                }
            }
            if (0 < $store_id) {
                $sql = 'UPDATE ' . $prefix . 'store_goods' . ' SET  goods_number = ' . $set_update . " \r\n                        WHERE goods_id = '" . $goods_id . '\' AND store_id = \'' . $store_id . "' \r\n                        LIMIT 1";
                $table_b = $this->notorm->store_goods;
            } else if ($goods['model_inventory'] == 1) {
                $sql = 'UPDATE ' . $prefix . 'warehouse_goods' . ' SET  region_number = ' . $set_update . " \r\n                            WHERE goods_id = '" . $goods_id . '\' and region_id = \'' . $warehouse_id . "' \r\n                            LIMIT 1";
                $table_b = $this->notorm->warehouse_goods;
            } else if ($goods['model_inventory'] == 2) {
                $sql = 'UPDATE ' . $prefix . 'warehouse_area_goods' . ' SET  region_number = ' . $set_update . " \r\n                            WHERE goods_id = '" . $goods_id . '\' and region_id = \'' . $area_id . "'  \r\n                            LIMIT 1";
                $table_b = $this->notorm->warehouse_area_goods;
            } else {
                $sql = 'UPDATE ' . $prefix . 'goods' . ' SET  goods_number = ' . $set_update . " \r\n                            WHERE goods_id = '" . $goods_id . "' \r\n                            LIMIT 1";
                $table_b = $this->notorm->goods;
            }
            $table_b->queryAll($sql);
        }
        $logs_other = array('goods_id' => $goods_id, 'order_id' => $order_id, 'use_storage' => 0, 'admin_id' => 0, 'number' => $number, 'model_inventory' => $goods['model_inventory'], 'model_attr' => $goods['model_attr'], 'product_id' => $product_id, 'warehouse_id' => $warehouse_id, 'area_id' => $area_id, 'add_time' => gmtime());
        $this->notorm->goods_inventory_logs->insert($logs_other);
        return true;
    }

    /**
     * Name: 获取单个订单商品信息
     * User: wanghousheng
     * Date: 2016/12/27
     * @param $id
     * @return mixed
     */
    protected function get_order_goods_info($id)
    {
        $prefix = get_table_prefix();
        $sql = 'SELECT og.goods_name, og.goods_number, g.goods_thumb, og.goods_attr, og.goods_price, IF(og.extension_code = \'package_buy\', (SELECT activity_thumb FROM ' . $prefix . 'goods_activity' . " WHERE act_id = g.goods_id),g.goods_thumb) as goods_thumb\r\n\t\t\tFROM " . $prefix . 'order_goods' . ' AS og' . ' LEFT JOIN ' . $prefix . 'goods' . ' AS g ON  og.goods_id = g.goods_id' . ' WHERE og.rec_id = ' . $id;
        $goods = $this->notorm->order_goods->queryRows($sql);
        return $goods[0];
    }

    /**
     * 支付方式列表
     * @return array
     */
    protected function payment_list()
    {

        $payment = \PhalApi\DI()
            ->notorm
            ->payment
            ->select('pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod')
            ->where('enabled', 1)
            ->order('pay_order')
            ->fetchAll();
        return is_array($payment) ? $payment : array();
    }

    /**
     * 支付方式
     * @return array
     */
    protected function paymentinfo($payid)
    {

        $payment = \PhalApi\DI()
            ->notorm
            ->payment
            ->select('pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod')
            ->where(array('enabled' => 1, 'pay_id' => $payid))
            ->fetchOne();
        return is_array($payment) ? $payment : array();
    }

    /**
     * 取得支付方式id列表
     * @param   bool $is_cod 是否货到付款
     * @return  array
     */
    protected function payment_id_list($is_cod = true)
    {
        if ($is_cod) {
            $where['is_cod'] = 1;
        } else {
            $where['is_cod'] = 0;
        }
        return $this->medoo->select('payment', 'pay_id', $where);
    }

    protected function order_lang()
    {
        //订单状态
        $data['os'][OS_UNCONFIRMED] = '未确认';
        $data['os'][OS_CONFIRMED] = '已确认';
        $data['os'][OS_SPLITED] = '已确认';
        $data['os'][OS_SPLITING_PART] = '已确认';
        $data['os'][OS_CANCELED] = '已取消';
        $data['os'][OS_INVALID] = '无效';
        $data['os'][OS_RETURNED] = '退货';
        $data['os'][7] = '部分已退货';
        //配送
        $data['ss'][SS_UNSHIPPED] = '未发货';
        $data['ss'][SS_PREPARING] = '配货中';
        $data['ss'][SS_SHIPPED] = '已发货';
        $data['ss'][SS_RECEIVED] = '收货确认';
        $data['ss'][SS_SHIPPED_PART] = '已发货(部分商品)';
        $data['ss'][SS_SHIPPED_ING] = '配货中'; // 已分单
        //支付
        $data['ps'][PS_UNPAYED] = '未付款';
        $data['ps'][PS_PAYING] = '付款中';
        $data['ps'][PS_PAYED] = '已付款';
        $data['ps'][PS_PAYED_PART] = '部分付款(定金)';
        return $data;
    }
}